package cn.hairui.fastms.core.controller;


import cn.hairui.fastms.base.cache.CacheManage;
import cn.hairui.fastms.base.config.WebLogInfo;
import cn.hairui.fastms.constant.FieldConstant;
import cn.hairui.fastms.constant.GlobalConstant;
import cn.hairui.fastms.core.bean.SResc;
import cn.hairui.fastms.core.bean.SRoleResc;
import cn.hairui.fastms.core.bean.SUser;
import cn.hairui.fastms.core.service.SRescService;
import cn.hairui.fastms.core.service.SRoleRescService;
import cn.hairui.fastms.util.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 资源信息表 前端控制器
 * </p>
 *
 * @author lihairui
 * @since 2020-11-29
 */
@Controller
@RequestMapping("/sResc")
public class SRescController {
    @Autowired
    private SRescService sRescService;
    @Autowired
    private SRoleRescService sRoleRescService;

    @WebLogInfo(description = "获取资源菜单")
    @RequestMapping(value = "/menu")
    @ResponseBody
    public String menu(HttpServletRequest request, String menuId) {
        SUser sUser = (SUser) request.getSession().getAttribute(GlobalConstant.GLOBAL_SESSION_NAME);
        String userAccount = null;
        if (sUser == null) {
            return "/login";
        } else {
            userAccount = sUser.getUserAccount();
        }
        QueryWrapper<SResc> queryWrapper = new QueryWrapper<>();
        if (menuId != null && !"".equals(menuId)) {
            queryWrapper.eq(FieldConstant.RESC_PARENTID[0], menuId);
        } else {
            queryWrapper.eq(FieldConstant.RESC_PARENTID[0], GlobalConstant.PARENT_RESC_ID_MAX);
        }
        //List<SResc> sRescList = sRescService.list(queryWrapper);//所有子菜单权限

        List<SResc> sRescList = sRescService.selectMenuByAccount(userAccount, menuId);//根据系统规则获取用户可以访问的子菜单
        //Iterator iterator = sRescList.iterator();
        //JSONArray jsonArray = new JSONArray();
        String result = "";
        for (int i = 0; i < sRescList.size(); i++) {
            SResc sResc = sRescList.get(i);
            String status = "";
            String statusText = "";
            if (sResc.getRescUrl() != null && !"".equals(sResc.getRescUrl())) {
                status = "open";
                statusText = "子节点";
            } else {
                status = "closed";
                statusText = "父节点";
            }
            String url = "";
            if (sResc.getRescUrl() != null) {
                url = sResc.getRescUrl();
            }
            result = result + "  {\n" +
                    "    \"id\": \"" + sResc.getRescCde() + "\",\n" +
                    "    \"pid\": \"" + sResc.getRescParentid() + "\",\n" +
                    "    \"text\": \"" + sResc.getRescDesc() + "\",\n" +
                    "    \"state\": \"" + status + "\",\n" +
                    "    \"stateText\": \"" + statusText + "\",\n" +
                    "    \"iconCls\": \"" + sResc.getRescIcon() + "\",\n" +
                    "    \"url\": \"" + url + "\"\n";
            if (i + 1 == sRescList.size()) {
                result = result + "  }";
            } else {
                result = result + "  },\n";
            }

            /*JSONObject jsonObject = new JSONObject();
            jsonObject.appendField("id", sResc.getRescCde());
            jsonObject.appendField("pid", sResc.getRescParentid());
            jsonObject.appendField("text", sResc.getRescDesc());
            if (sResc.getRescUrl() != null && !"".equals(sResc.getRescUrl())) {
                jsonObject.appendField("status", "open");
            } else {
                jsonObject.appendField("status", "closed");
            }
            jsonObject.appendField("iconCls", sResc.getRescIcon());
            jsonObject.appendField("url", sResc.getRescUrl() == null ? "" : sResc.getRescUrl());
            jsonArray.add(jsonObject);*/
        }
        /*return jsonArray;*/
        return "[\n" + result + "]";
    }

    @WebLogInfo(description = "获取资源定义菜单")
    @RequestMapping(value = "/menuD")
    @ResponseBody
    public String menuD(HttpServletRequest request, String menuId) {

        QueryWrapper<SResc> queryWrapper = new QueryWrapper<>();
        if (menuId != null && !"".equals(menuId)) {
            queryWrapper.eq(FieldConstant.RESC_PARENTID[0], menuId);
        } else {
            queryWrapper.eq(FieldConstant.RESC_PARENTID[0], GlobalConstant.PARENT_RESC_ID_MAX);
        }
        List<SResc> sRescList = sRescService.list(queryWrapper);//所有子菜单权限
        //Iterator iterator = sRescList.iterator();
        //JSONArray jsonArray = new JSONArray();
        String result = "";
        for (int i = 0; i < sRescList.size(); i++) {
            SResc sResc = sRescList.get(i);
            String status = "";
            String statusText = "";
            if (sResc.getRescUrl() != null && !"".equals(sResc.getRescUrl())) {
                status = "open";
                statusText = "子节点";
            } else {
                status = "closed";
                statusText = "父节点";
            }
            String url = "";
            if (sResc.getRescUrl() != null) {
                url = sResc.getRescUrl();
            }
            result = result + "  {\n" +
                    "    \"id\": \"" + sResc.getRescCde() + "\",\n" +
                    "    \"pid\": \"" + sResc.getRescParentid() + "\",\n" +
                    "    \"text\": \"" + sResc.getRescDesc() + "\",\n" +
                    "    \"state\": \"" + status + "\",\n" +
                    "    \"stateText\": \"" + statusText + "\",\n" +
                    "    \"iconCls\": \"" + sResc.getRescIcon() + "\",\n" +
                    "    \"url\": \"" + url + "\"\n";
            if (i + 1 == sRescList.size()) {
                result = result + "  }";
            } else {
                result = result + "  },\n";
            }

            /*JSONObject jsonObject = new JSONObject();
            jsonObject.appendField("id", sResc.getRescCde());
            jsonObject.appendField("pid", sResc.getRescParentid());
            jsonObject.appendField("text", sResc.getRescDesc());
            if (sResc.getRescUrl() != null && !"".equals(sResc.getRescUrl())) {
                jsonObject.appendField("status", "open");
            } else {
                jsonObject.appendField("status", "closed");
            }
            jsonObject.appendField("iconCls", sResc.getRescIcon());
            jsonObject.appendField("url", sResc.getRescUrl() == null ? "" : sResc.getRescUrl());
            jsonArray.add(jsonObject);*/
        }
        /*return jsonArray;*/
        return "[\n" + result + "]";
    }

    @WebLogInfo(description = "获取下拉可选资源菜单")
    @RequestMapping(value = "/menuS")
    @ResponseBody
    public String menuS(HttpServletRequest request, String menuId) {
        QueryWrapper<SResc> queryWrapper = new QueryWrapper<>();
        String result = "";
        if (menuId != null && !"".equals(menuId)) {
            queryWrapper.eq(FieldConstant.RESC_PARENTID[0], menuId).and(wrapper -> wrapper
                    .isNull(FieldConstant.RESC_URL[0]).or()
                    .eq(FieldConstant.RESC_URL[0], "")
            );
        } else {
            queryWrapper.eq(FieldConstant.RESC_PARENTID[0], GlobalConstant.PARENT_RESC_ID_MAX).and(wrapper -> wrapper
                    .isNull(FieldConstant.RESC_URL[0]).or()
                    .eq(FieldConstant.RESC_URL[0], "")
            );
        }
        SResc sRescR = new SResc();
        sRescR.setRescCde(GlobalConstant.PARENT_RESC_ID_MAX);
        sRescR.setRescParentid("");
        sRescR.setRescDesc("根节点");
        sRescR.setRescIcon("fa fa-folder");

        List<SResc> sRescList = new ArrayList<>();
        if (menuId == null || "".equals(menuId)) {
            sRescList.add(sRescR);
        } else {
            sRescList = sRescService.list(queryWrapper);
        }
        for (int i = 0; i < sRescList.size(); i++) {
            SResc sResc = sRescList.get(i);
            String status = "";
            String statusText = "";
            if (sResc.getRescUrl() != null && !"".equals(sResc.getRescUrl())) {
                status = "open";
                statusText = "子节点";
            } else {
                status = "closed";
                statusText = "父节点";
            }
            String url = "";
            if (sResc.getRescUrl() != null) {
                url = sResc.getRescUrl();
            }
            result = result + "  {\n" +
                    "    \"id\": \"" + sResc.getRescCde() + "\",\n" +
                    "    \"pid\": \"" + sResc.getRescParentid() + "\",\n" +
                    "    \"text\": \"" + sResc.getRescDesc() + "\",\n" +
                    "    \"state\": \"" + status + "\",\n" +
                    "    \"stateText\": \"" + statusText + "\",\n" +
                    "    \"iconCls\": \"" + sResc.getRescIcon() + "\",\n" +
                    "    \"url\": \"" + url + "\"\n";
            if (i + 1 == sRescList.size()) {
                result = result + "  }";
            } else {
                result = result + "  },\n";
            }
        }
        return "[\n" + result + "]";
    }

    @WebLogInfo(description = "资源定义列表页面")
    @RequestMapping(value = "/list")
    public String list(HttpServletRequest request) {
        return "pages/core/sresc/sresc";
    }

    @WebLogInfo(description = "资源定义新增页面")
    @RequestMapping(value = "/add")
    public String add(HttpServletRequest request) {
        return "pages/core/sresc/srescAdd";
    }

    @WebLogInfo(description = "资源定义编辑页面")
    @RequestMapping(value = "/edit")
    public String edit(HttpServletRequest request) {
        return "pages/core/sresc/srescEdit";
    }

    @WebLogInfo(description = "资源定义详细数据获取")
    @RequestMapping(value = "/detail")
    @ResponseBody
    public JSONObject data(HttpServletRequest request, String menuId) {
        QueryWrapper<SResc> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(FieldConstant.RESC_CDE[0], menuId);
        SResc sResc = sRescService.getOne(queryWrapper);
        JSONObject json = JSONObject.fromObject(sResc);
        return json;
    }

    @WebLogInfo(description = "资源定义数据保存")
    @RequestMapping(value = "/save")
    @ResponseBody
    public String save(HttpServletRequest request, SResc sResc, String flag) {
        SUser currentUser = (SUser) request.getSession().getAttribute(GlobalConstant.GLOBAL_SESSION_NAME);
        if (GlobalConstant.OPERATION_ADD.equals(flag)) {
            //新增保存
            sResc.setUpdateTime(DateUtil.getCurrentDateTimeStr());
            sResc.setUpdateUser(currentUser.getUserAccount());
            //判断是否已经存在
            QueryWrapper<SResc> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(FieldConstant.RESC_CDE[0], sResc.getRescCde());

            if (sRescService.list(queryWrapper).size() > 0) {
                //已存在资源 不允许新增
                return CacheManage.msgMap.get(GlobalConstant.MSG_CDE_S0003).toJSONString();
            } else {
                //不存在资源 允许新增
                sRescService.save(sResc);
                return CacheManage.msgMap.get(GlobalConstant.MSG_CDE_S0000).toJSONString();
            }

        } else if (GlobalConstant.OPERATION_EDIT.equals(flag)) {
            //更新保存
            boolean result = sRescService.saveOrUpdate(sResc);
            if (result) {
                //更新成功
                return CacheManage.msgMap.get(GlobalConstant.MSG_CDE_S0000).toJSONString();
            } else {
                //更新失败
                return CacheManage.msgMap.get(GlobalConstant.MSG_CDE_S0001).toJSONString();
            }
        } else {
            return null;
        }
    }

    @WebLogInfo(description = "资源定义数据删除")
    @RequestMapping(value = "/delete")
    @ResponseBody
    @Transactional
    public String delete(HttpServletRequest request, String[] rescCde) {
        QueryWrapper<SResc> queryWrapper = new QueryWrapper<>();
        queryWrapper.in(FieldConstant.RESC_PARENTID[0], rescCde);

        if (sRescService.list(queryWrapper).size() > 0) {
            return CacheManage.msgMap.get(GlobalConstant.MSG_CDE_S0001).toJSONString();
        } else {
            QueryWrapper<SResc> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.in(FieldConstant.RESC_CDE[0], rescCde);
            sRescService.remove(queryWrapper2);

            //级联删除角色资源信息
            QueryWrapper<SRoleResc> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.in(FieldConstant.RESC_CDE[0], rescCde);
            sRoleRescService.remove(queryWrapper3);

            return CacheManage.msgMap.get(GlobalConstant.MSG_CDE_S0000).toJSONString();
        }
    }

}

